package cd.safe.school.adapter;

import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import cd.safe.school.R;

public class GridItemAdapter extends BaseAdapter {
	private List<String> list;
	private Context context;

	public GridItemAdapter(List<String> list, Context context) {
		this.context = context;
		this.list = list;

	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			LayoutInflater in = LayoutInflater.from(context);
			convertView = in.inflate(R.layout.grid_item, null);
		}
		ImageView grid_item = (ImageView) convertView
				.findViewById(R.id.grid_item);
		Button remove = (Button) convertView.findViewById(R.id.remove_gridimg);

		remove.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				list.remove(position);
				notifyDataSetChanged();

			}
		});

		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;

		Bitmap bm = BitmapFactory.decodeFile(list.get(position), options);
		float realWidth = options.outWidth;
		float realHeight = options.outHeight;
		int scale = (int) ((realHeight > realWidth ? realHeight : realWidth) / 100);
		if (scale <= 0) {
			scale = 1;
		}
		options.inSampleSize = scale;
		options.inJustDecodeBounds = false;
		bm = BitmapFactory.decodeFile(list.get(position), options);

		grid_item.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
		grid_item.setImageBitmap(bm);

		return convertView;
	}
}
